﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.WareHoustForm;
using BW.Mes.WinForms.BasicData;
using BW.Mes.WinForms;
using BW.Mes.WinForms.Process.ProcessModel;

namespace BW.Mes.WinForms.BasicData
{
    public partial class WorkshopForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _workshopApiBaseUrl = "http://120.26.197.100:8022";
        private List<WorkShopModel> _allWorkshops = new List<WorkShopModel>(); // 保存所有数据

        // 1. 定义分页DTO
        public class WorkshopPageResult
        {
            public int totalCount { get; set; }
            public List<WorkShopModel> pageDatas { get; set; }
            public string message { get; set; }
            public object data { get; set; }
            public int code { get; set; }
        }

        public WorkshopForm()
        {
            InitializeComponent();
            //初始化httpClient, 忽略SSL证书验证
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
            };
            _httpClient = new HttpClient(handler);
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 设置斑马纹背景色
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.OptionsView.EnableAppearanceOddRow = true;
            gridView1.Appearance.EvenRow.BackColor = ColorTranslator.FromHtml("#fde6f4"); // 使用自定义粉色
            gridView1.Appearance.OddRow.BackColor = Color.White;
            gridView1.Appearance.HeaderPanel.BackColor = ColorTranslator.FromHtml("#fde6f4"); // 设置表头为粉色
            gridView1.Appearance.HeaderPanel.Options.UseBackColor = true;

            // 车间管理斑马纹：偶数行#fde6f4，奇数行#fff6fb
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.OptionsView.EnableAppearanceOddRow = true;
            gridView1.Appearance.EvenRow.BackColor = ColorTranslator.FromHtml("#fde6f4");
            gridView1.Appearance.EvenRow.Options.UseBackColor = true;
            gridView1.Appearance.OddRow.BackColor = ColorTranslator.FromHtml("#fff6fb");
            gridView1.Appearance.OddRow.Options.UseBackColor = true;
            gridView1.Appearance.FocusedRow.BackColor = Color.Transparent;
            gridView1.Appearance.FocusedRow.Options.UseBackColor = false;
            gridView1.Appearance.HideSelectionRow.BackColor = Color.Transparent;
            gridView1.Appearance.HideSelectionRow.Options.UseBackColor = false;

            // 设置所有按钮为粉色
            foreach (Control ctrl in this.Controls)
            {
                if (ctrl is DevExpress.XtraEditors.SimpleButton simpleBtn)
                {
                    simpleBtn.Appearance.BackColor = ColorTranslator.FromHtml("#fde6f4");
                    simpleBtn.Appearance.Options.UseBackColor = true;
                    simpleBtn.LookAndFeel.UseDefaultLookAndFeel = false;
                }
                else if (ctrl is Button btn)
                {
                    btn.BackColor = ColorTranslator.FromHtml("#fde6f4");
                    btn.FlatStyle = FlatStyle.Flat;
                }
            }

            // 窗体加载时获取数据
            this.Load += WorkshopForm_Load;
            // 设置序号列为自增
            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
            gridView1.CustomColumnDisplayText += gridView1_CustomColumnDisplayText;

            // 支持多选和复选框列
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
        }
        // 1. 修改分页数据加载方法
        private async Task LoadWorkshopData(int pageIndex, int pageSize)
        {
            try
            {
                string url = $"T2/Workshop/GetWorkshop?PageIndex={pageIndex}&PageSize={pageSize}";
                WorkshopPageResult result = null;
                List<WorkShopModel> data = null;
                int totalCount = pagerControl1.TotalCount; // 默认保留原有总数
                try
                {
                    result = await GetApiDataAsync<WorkshopPageResult>(url);
                    data = result?.pageDatas ?? new List<WorkShopModel>();
                    totalCount = result?.totalCount ?? 0;
                }
                catch
                {
                    // 如果返回的是数组
                    data = await GetApiDataAsync<List<WorkShopModel>>(url);
                    // totalCount 不变，避免分页控件失效
                }
                gridControl1.DataSource = data;
                pagerControl1.TotalCount = totalCount;
                pagerControl1.PageIndex = pageIndex;
                pagerControl1.PageSize = pageSize;
                gridView1.PopulateColumns();
                var idColumn = gridView1.Columns["Id"];
                if (idColumn != null) idColumn.Visible = false;
                EnsureSerialNumberColumn();
                gridView1.BestFitColumns();
                gridView1.RefreshData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据失败: {ex.Message}", "错误");
            }
        }
        /// <summary>
        /// 获取车间
        /// </summary>
        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_workshopApiBaseUrl}/{endpoint}");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                // 直接反序列化整个对象
                return JsonConvert.DeserializeObject<T>(responseBody);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        // 提交数据到API
        public async Task<bool> PostApiDataAsync<T>(string endpoint, T data)
        {
            try
            {
                string jsonData = JsonConvert.SerializeObject(data);
                HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PostAsync($"{_workshopApiBaseUrl}/{endpoint}", content);
                response.EnsureSuccessStatusCode();
                return true;
            }
            catch (Exception ex)
            {
                var errorMessage = $"提交数据失败: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMessage += $"\n内部错误: {ex.InnerException.Message}";
                }
                errorMessage += $"\n\n请确保后端服务正在运行，并且地址 {_workshopApiBaseUrl} 正确无误。";
                XtraMessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        public class WorkShopModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 车间名称
            /// </summary>
            [DisplayName("车间编号")]
            public string WorkshopCode { get; set; }
            // 车间编号
            [DisplayName("车间名称")]
            public string WorkshopName { get; set; }
            // 车间描述
            [DisplayName("车间描述")]
            [System.ComponentModel.DataAnnotations.StringLength(50, ErrorMessage = "车间描述不能超过50个字符")]
            public string WorkshopMsg { get; set; }
            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("更新时间")]
            public DateTime CreatedAt { get; set; } = DateTime.Now;
            [DisplayName("修改时间")]
            public DateTime? UpdatedAt { get; set; }
        }

        // 2. 绑定分页控件事件和初始化加载
        private async void WorkshopForm_Load(object sender, EventArgs e)
        {
            pagerControl1.PageChanged += async (s, e2) =>
            {
                await LoadWorkshopData(pagerControl1.PageIndex, pagerControl1.PageSize);
            };
            await LoadWorkshopData(1, pagerControl1.PageSize);
        }

        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            await LoadWorkshopData(pagerControl1.PageIndex, pagerControl1.PageSize);
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            var addForm = new AddWorkshopForm();
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                await LoadWorkshopData(pagerControl1.PageIndex, pagerControl1.PageSize);
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadWorkshopData(pagerControl1.PageIndex, pagerControl1.PageSize);
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            LoadWorkshopData(1, pagerControl1.PageSize);
        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.ListSourceRowIndex >= 0)
            {
                e.DisplayText = (e.ListSourceRowIndex + 1).ToString();
            }
        }

        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        private async void btnDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的车间！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var confirm = XtraMessageBox.Show($"确定要删除选中的 {selectedRows.Length} 个车间吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;

            int successCount = 0;
            int failureCount = 0;

            foreach (var rowHandle in selectedRows)
            {
                var workshop = gridView1.GetRow(rowHandle) as WorkShopModel;
                if (workshop != null)
                {
                    if (await DeleteWorkshop(workshop.Id))
                    {
                        successCount++;
                    }
                    else
                    {
                        failureCount++;
                    }
                }
            }

            if (failureCount == 0)
            {
                XtraMessageBox.Show($"成功删除 {successCount} 个车间。", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show($"成功删除 {successCount} 个车间，{failureCount} 个车间删除失败。", "操作完成", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            await LoadWorkshopData(pagerControl1.PageIndex, pagerControl1.PageSize);
        }

        private async Task<bool> DeleteWorkshop(long id)
        {
            try
            {
                var response = await _httpClient.PutAsync($"{_workshopApiBaseUrl}/T2/Workshop/DeleteWorkshop?id={id}", null);
                var responseContent = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                    if (apiResult != null && apiResult.code == 200)
                    {
                        return true;
                    }
                    else
                    {
                        string errorMessage = apiResult?.message ?? "删除失败，未知错误";
                        XtraMessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
                else
                {
                    string errorMessage = $"HTTP错误：{response.StatusCode}";
                    try
                    {
                        var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (apiResult != null && !string.IsNullOrEmpty(apiResult.message))
                        {
                            errorMessage = apiResult.message;
                        }
                    }
                    catch { }
                    XtraMessageBox.Show($"删除失败：{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除异常: {ex.Message}", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length != 1)
            {
                XtraMessageBox.Show("请只选择一条要修改的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var workshop = gridView1.GetRow(selectedRows[0]) as WorkShopModel;
            if (workshop == null)
            {
                XtraMessageBox.Show("未获取到车间信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var updateForm = new UpdateWorkshopForm(workshop);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                LoadWorkshopData(pagerControl1.PageIndex, pagerControl1.PageSize);
            }
        }

        private void panelControl1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}